import { Context, PlainObject } from "egg";
import { Op } from "sequelize";
import helper from "../helper";
import EntityDao from "../dao";
import { DaoService } from "../mvc";

export default class ApplicationService extends DaoService {
  constructor(ctx: Context) {
    super(ctx);
    this.dao = new EntityDao(ctx, ctx.model.Application, [
      {
        model: ctx.model.Platform,
        as: "platform"
      }
    ]);
  }

  /**
   * 添加应用
   * @param data
   * @returns
   */
  async create(data: any) {
    return await this.dao.create(data, ["pltId", "appName", "appCode"]);
  }

  /**
   * 删除应用
   * @param appId 应用Id
   * @returns
   */
  async destroy(appId: string): Promise<ServiceResponse> {
    return await this.dao.destroy(appId);
  }

  /**
   * 修改应用
   * @param appId
   * @param data
   * @returns
   */
  async update(appId: string, data: any): Promise<ServiceResponse> {
    return await this.dao.update(appId, data, ["pltId", "appName", "appCode"]);
  }

  /**
   * 查询应用列表
   * @param query ctx.request.query
   * @returns
   */
  async index(query: PlainObject<string>): Promise<ServiceResponse> {
    const where: any = {};
    if (!helper.isEmpty(query.appName)) {
      where.appName = query.appName;
    }
    return await this.dao.index(where);
  }

  /**
   * 查询应用明细明细
   * @param appId
   * @returns
   */
  async show(appId: string): Promise<ServiceResponse> {
    return await this.dao.show(appId);
  }

  /**
   * 查询应用分页列表
   * @param query ctx.request.query
   * @returns
   */
  async page(query: PlainObject<string>): Promise<ServiceResponse> {
    const where: any = {};
    if (!helper.isEmpty(query.appName)) {
      where.appName = { [Op.like]: `%${query.appName}%` };
    }
    return await this.dao.page({ current: query.current, pageSize: query.pageSize, where });
  }
}
